package com.jiepos.mpos.core.util;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
* 描述: xml工具类，首先通过XmlUtil.getInstance("c:/cc.xml")获取一个实例，然后对其操作<
* 模块: 通用平台
* @author  娄伟峰
* @version 1.0
 */
public class XmlUtil {
	
	public final static Logger log = LoggerFactory.getLogger(XmlUtil.class);

	
	/** xml文档 */
	private Document document;
	
	/** xml文件路径 */
	private String xmlPath;
	
	private XmlUtil(String xmlPath) {
		this.xmlPath = xmlPath;
		// 初始化xml文档
		initDocument(xmlPath);
	}
	
	private XmlUtil(InputStream in) {
		// 初始化xml文档
		initDocument(in);
	}
 
	/**
	 * 初始化xml文档
	 * @param in
	 */
	private void initDocument(InputStream in) {
		SAXReader reader = new SAXReader();
		try {
			document = reader.read(in);
		} catch (DocumentException e) {
			log.debug("read xml error：", e);
		}
	}

	/**
	 * 初始化xml文档
	 * @param xmlPath
	 */
	private void initDocument(String xmlPath) {
		SAXReader reader = new SAXReader();
		try {
			document = reader.read(xmlPath);
		} catch (DocumentException e) {
			log.debug("read xml error：" + xmlPath, e);
		}
	}
	
	/**
	 * 获取XmlUtil实例
	 * @param xmlPath
	 * @return
	 */
	public static XmlUtil getInstance(String xmlPath) {
		if (!FileUtils.isExist(xmlPath)) {
			log.debug("create XMLUtil failed,invalid path:" + xmlPath);
			throw new RuntimeException("create XMLUtil failed,invalid path:" + xmlPath);
		}
		return new XmlUtil(xmlPath);
	}
	
	/**
	 * 获取XmlUtil实例
	 * @param in 输入流
	 * @return
	 */
	public static XmlUtil getInstance(InputStream in) {
		return new XmlUtil(in);
	}
	
	/**
	 * 获取xPath指定的节点
	 * @param xPath
	 * @return 存在返回node, 不存在返回null
	 */
	public Node getNode(String xPath) {
		return document.selectSingleNode(xPath);
	}
	
	/**
	 * 获取某个PATH对应的元素的文本
	 * @param xPath
	 * @return
	 */
	public String getNodeText(String xPath) {
		String rs = "";
		Node node = document.selectSingleNode(xPath);
		if (node != null) {
			rs = node.getText();
		}
		return rs;
	}
	
	/**
	 * 设置xPath对应的节点文本内容
	 * @param xPath 节点路径
	 * @param text 文本内容
	 */
	public void setNodeText(String xPath, String text) {
		Node node = document.selectSingleNode(xPath);
		if (node != null) {
			node.setText(text);
		}
		save();
	}
	
	/**
	 * 设置节点的CDATA文本
	 * @param xPath
	 * @param text
	 */
	public void setNodeCDATAText(String xPath, String text) {
		Element element = (Element) document.selectSingleNode(xPath);
		element.setText("");
		element.addCDATA(text);
	}
	
	/**
	 * 保存修改后的文档
	 */
	public void save() {
		if (xmlPath == null) {
			throw new RuntimeException("wrtie xml error: xmlPath is null");
		}
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream(xmlPath));
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			log.debug("write xml error: ", e);
		}
	}
	
	/**
	 * 保存修改后的文档
	 * @param xmlPath 另存为文件的路径
	 */
	public void save(String xmlPath) {
		if (xmlPath == null) {
			throw new RuntimeException("wrtie xml error: xmlPath is null");
		}
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream(xmlPath));
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			log.debug("write xml error: ", e);
		}
	}
	
	public static void main(String[] args) {
/*		XmlUtil xmlUtil = XmlUtil.getInstance("c:/proxoolconf.xml");
		System.out.println(xmlUtil.getNodeText("/something-else-entirely/proxool/driver-class"));
		XmlUtil xmlUddtil = XmlUtil.getInstance("c:/proxoolconf.xml");
		System.out.println(xmlUddtil.getNodeText("/something-else-entirely/proxool/driver-properties/property"));
		xmlUtil.setNodeCDATAText("/something-else-entirely/proxool/driver-class", "在哪里因");
		System.out.println(xmlUtil.getNodeText("/something-else-entirely/proxool/driver-class"));
		xmlUtil.save("c:/ss.xml");*/
		
		String str ="<package><header><errCode>3001</errCode><errMsg>金额格式错误！</errMsg><succeed>false</succeed><timeStamp>20151229190657</timeStamp></header><body><md5>C895810735284784FB23EEC12883E70F</md5></body></package>";
		InputStream in = null;
		 
			in = new ByteArrayInputStream(str.getBytes());
	 
		XmlUtil tempXml = XmlUtil.getInstance(in);
		String succeed = tempXml.getNodeText("/package/header/sd");
		System.out.println(succeed);
	}
	
}
